package core.router;

import java.util.Timer;
import java.util.TimerTask;

import core.schedulers.SchedulerKind;

public class Router {

	private Worker lanWorker;
	private Worker netWorker;
	private double bandwidth;
		
	private Timer timer;
	private final int INITIAL_DELAY = 1;

	private boolean lanTime = false;
	
	public Router(long queueCapacity, double bandwidth) {
		lanWorker = new Worker(queueCapacity, SchedulerKind.LAN);
		netWorker = new Worker(queueCapacity, SchedulerKind.INTERNET);
		this.bandwidth = bandwidth;
		
        timer = new Timer();
        timer.schedule(new RemindTask(), INITIAL_DELAY);
	}
	
    class RemindTask extends TimerTask {
        public void run() {
			double processTime = process();
			if (processTime != 0)
				System.out.println("=== Tempo de processamento: " + processTime + " ms. ===");
    		timer.schedule(new RemindTask(), (int) processTime);
        }
    }

	private double process() {

		double packetSize = 0;
		if (lanWorker.hasPacket() && (lanTime || !netWorker.hasPacket())) {
			System.out.println("=== Iniciando o processamento de um pacote ===");
			packetSize = lanWorker.process().getSize();
			lanTime = false;
			System.out.println("=== Fim do processamento de um pacote === ");
		} else if (netWorker.hasPacket() && (!lanTime || !lanWorker.hasPacket())) {
			System.out.println("=== Iniciando o processamento de um pacote ===");
			packetSize = netWorker.process().getSize();
			lanTime = true;
			System.out.println("=== Fim do processamento de um pacote === ");
		}
		double processTime = (packetSize * 1000)/bandwidth;
		return processTime == 0? 0: Math.max(processTime, 1);
	}
	
	public Worker getLanWoker(){
		return lanWorker;
	}
	
	public Worker getNetWorker(){
		return netWorker;
	}
}
